<?php
namespace app\notify\controller;
use EasyWeChat\Factory;
use EasyWeChat\Kernel\Messages\Message;
use app\common\model\Mall as MallModel;
use app\common\model\User as UserModel;
use app\common\model\UserWechat as UserWechatModel;

use app\service\WechatService;
use app\service\UserService;

class Event extends Base
{
    public static $mall;
    public static $openPlatform;
    public static $app;
    public function __construct () 
    {
        parent::__construct();
        $config = [
            'app_id'   => config('open_appid'),
            'secret'   => config('open_secret'),
            'token'    => config('open_token'),
            'aes_key'  => config('open_aeskey'),
            'response_type' => 'array',
            'oauth' => [
                'scopes'   => ['snsapi_userinfo'],
                'callback' => '/index/login/wechat_callback',
            ]
        ];
        self::$openPlatform = Factory::openPlatform($config);
    }
    public function index($appid) 
    {
        //微信官方自动化测试
        // || $appid=='wx6c3a37e2c19b248c' || true
        if($appid=='wx570bc396a51b8ff8') {
            $officialAccount = self::$openPlatform->officialAccount($appid);
            $server = $officialAccount->server; // ❗️❗️  这里的 server 为授权方的 server，而不是开放平台的 server，请注意！！！
            $message = $server->getMessage();
            if($message['Content']=='TESTCOMPONENT_MSG_TYPE_TEXT') {
                $server->push(function ($message) {
                    return 'TESTCOMPONENT_MSG_TYPE_TEXT_callback';
                });
            }elseif(strstr($message['Content'],'QUERY_AUTH_CODE')){
                $query_auth_code = str_replace('QUERY_AUTH_CODE:','',$message['Content']);
                //客服消息
                $Authorize = self::$openPlatform->handleAuthorize($query_auth_code);
                $mallInfo = [
                    'authorizer_appid' => $Authorize['authorization_info']['authorizer_appid'],
                    'authorizer_access_token' => $Authorize['authorization_info']['authorizer_access_token'],
                    'authorizer_refresh_token' => $Authorize['authorization_info']['authorizer_refresh_token'],
                ];
                //file_put_contents(ROOT_PATH.'log.txt','MALL_INFO'.json_encode($Authorize).PHP_EOL,FILE_APPEND);
                config($mallInfo);
                $openid=$message['FromUserName'];
                $re = @WechatService::S()->send(WechatService::$msgType_text,$openid,$query_auth_code.'_from_api');
                $server->push(function ($message) {
                    return '';
                });
            }
            return $server->serve()->send();
        }
        self::$mall = MallModel::getOne(['authorizer_appid'=>$appid]);
        self::$app = self::$openPlatform->officialAccount($appid, self::$mall['authorizer_refresh_token']);
        $server = self::$openPlatform->officialAccount($appid)->server; //这里的 server 为授权方的 server，而不是开放平台的 server，请注意！！！
        $message = $server->getMessage();
        //file_put_contents(ROOT_PATH.'log.txt',json_encode($message).PHP_EOL,FILE_APPEND);

        /* $server->push(function ($message) {
            return json_encode($message);
        }); */
        //$server->push([Event::class,'handleText'], Message::TEXT); 
        $server->push([Event::class,'handleEvent'], Message::EVENT); 

        return $server->serve()->send();
    }

    /* 文本消息处理器 */
    public static  function handleText ($message) {
        return json_encode($message);
    }

    /* 事件处理器 */
    public static  function handleEvent ($message) {
        if($message['Event']==='subscribe') {
            //关注事件 
            $info = self::$app->user->get($message['FromUserName']);
            $userInfo = [
                'mall_id' => self::$mall['id'],
                'openid' => $info['openid'],
                'nickname' => $info['nickname'],
                'sex' => $info['sex'],
                'language' => $info['language'],
                'city' => $info['city'],
                'province' => $info['province'],
                'country' => $info['country'],
                'headimgurl' => $info['headimgurl'],
                'unionid' => $info['unionid'],
                'subscribe' => $info['subscribe']
            ];
            $uid = UserService::S()->handleWechatUser($userInfo);
            return '';
        }elseif($message['Event']=='unsubscribe') {
            //取消关注事件
            UserWechatModel::where('openid',$message['FromUserName'])->update([
                'subscribe' => 0
            ]);
        }
        //return json_encode($message);
    }
}
